#!/bin/bash
set -e

PATH=/usr/local/bin:$PATH

#取公网IP
ip_services=(
    "ifconfig.me"
    "ipinfo.io/ip"
    "icanhazip.com"
    "ipecho.net/plain"
)
get_public_ip() {
    for service in "${ip_services[@]}"; do
        ip=$(curl -s "$service" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$')
        if [[ -n "$ip" ]]; then
            echo "$ip"
            return 0
        fi
    done
    return 1
}
LOCAL_IP=$(ip -4 route get 1.1.1.1 | grep -oP 'src \K\S+')
PRIV_IP=${PRIV_IP:-$LOCAL_IP}
PUB_IP=${PUB_IP:-$(get_public_ip)}
echo $PRIV_IP
echo $PUB_IP
cp /etc/rtpengine/rtpengine.conf.orig /etc/rtpengine/rtpengine.conf
cp /etc/rtpengine/rtpengine-recording.conf.orig /etc/rtpengine/rtpengine-recording.conf
sed -i -e "s/PRIV_IP/$PRIV_IP/g" /etc/rtpengine/rtpengine.conf
sed -i -e "s/PUB_IP/$PUB_IP/g" /etc/rtpengine/rtpengine.conf
rtpengine-recording --config-file /etc/rtpengine/rtpengine-recording.conf

if [ "$1" = 'rtpengine' ]; then
  shift
  exec rtpengine --config-file /etc/rtpengine/rtpengine.conf "$@"
fi
exec "$@"